<template>
  <div class="body">
    <div v-if="loadingShow" class="demo-spin-container" :style="{height:offsetheight+'px'}">
      <Spin size="large" fix></Spin>
    </div>
    <div  v-else id="container" :style="{height:offsetheight+'px'}"></div>
    <Modal
      width="1000"
      v-model="sceneModal"
      title="根据模板选择场景">
      <template>
        <Table border :columns="columns" :data="templateDataList">
          <template slot-scope="{ row, index }" slot="action">
            <Button type="primary" size="small" style="margin-right: 5px" @click="findSceneInfoList(row)">查询</Button>
          </template>
        </Table>
      </template>
    </Modal>
  </div>
</template>

<script>
import { getGridInfo } from '../../../../api/eventlist'
import { findGridSceneTemplateList, findSceneLabelList, findScenePlaceList } from '../../../../api/gridScene'
export default {
  props: {
    pickID: {
      type: String
    },
    pickGrade: {
      type: String
    }
  },
  mounted () {
    // 延迟加载，防止出现AMap not defined
    // setTimeout(() => {
    //   this.initMap()
    //   // this.createHeatMap();
    // }, 1000)
    this.init()
  },
  beforeDestroy () {
    this.map && this.map.destroy()
  },
  name: 'grid-scene-map',
  data () {
    return {
      offsetheight: document.documentElement.clientHeight - 145,
      loadingShow: true,
      map: null,
      heatmap: null,
      dataList: [],
      gridList: [],
      max: 500,
      zoom: 9,
      pickInfo: {},
      sceneModal: false,
      columns: [
        {
          title: '模板ID',
          key: 'id'
        },
        {
          title: '模板名称',
          key: 'name'
        },
        {
          title: '备注',
          key: 'remarks'
        },
        {
          title: '操作',
          slot: 'action',
          width: 150,
          align: 'center'
        }
      ],
      templateDataList: [],
      placeList: [],
      labelList: [],
      templateRowInfo: {}
    }
  },
  methods: {
    // 初始化地图，创建地图实例
    initMap () {
      this.map = new AMap.Map('container', {
        resizeEnable: true,
        center: [this.pickInfo.coordinate.lng, this.pickInfo.coordinate.lat],
        zoom: this.zoom
        // mapStyle: 'amap://styles/grey' // 极夜蓝
        // 自定义地图样式：https://lbs.amap.com/dev/mapstyle/index
      })
      this.createMaker()
      // this.createMassMarks()
      // this.createHeatMap()
      // this.createPolygon()
    },
    // 判断浏览区是否支持canvas
    isSupportCanvas () {
      let elem = document.createElement('canvas')
      return !!(elem.getContext && elem.getContext('2d'))
    },
    // 创建热力图
    createHeatMap () {
      if (!this.isSupportCanvas()) {
        return this.$Notice.error({
          title: '地图展示失败！',
          desc: '热力图仅对支持canvas的浏览器适用,您所使用的浏览器不能使用热力图功能,请换个浏览器试试。'
        })
      }
      let __this = this
      this.map.plugin(['AMap.Heatmap'], function () {
        // 初始化heatmap对象
        __this.heatmap = new AMap.Heatmap(__this.map, {
          visible: false,
          radius: 25, // 给定半径
          opacity: [0, 0.8]
        })
        // 设置数据集：该数据为北京部分“公园”数据
        __this.heatmap.setDataSet({
          data: __this.labelList,
          max: __this.max
        })
      })
    },
    // 创建标记点
    createMaker () {
      var marker = new AMap.Marker({
        position: new AMap.LngLat(this.pickInfo.coordinate.lng, this.pickInfo.coordinate.lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        title: this.pickInfo.name,
        icon: './img/poi-marker-red.png'
      })
      // 将创建的点标记添加到已有的地图实例：
      this.map.add(marker)
    },
    // 创建场所标记点
    createMassMarks () {
      // let data = []
      this.placeList.forEach(item => {
        console.log(item)
        try {
          let x = item.csc_mapjson.split(',')

          var icon = new AMap.Icon({
            size: new AMap.Size(15, 15), // 图标尺寸
            image: item.icon, // Icon的图像
            imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
            imageSize: new AMap.Size(15, 15) // 根据所设置的大小拉伸或压缩图片
          })
          console.log(icon)
          var marker = new AMap.Marker({
            position: new AMap.LngLat(x[0], x[1]), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: item.name,
            icon: icon,
            place_type: item.second_level_id
          })
          marker.on('click', function (e) {
            console.log('click', e)
          })
          this.map.add(marker)
        } catch (e) {
          console.log('加载场所标记点异常！', e)
        }
      })
    },
    // 绘制多边形
    createPolygon () {
      this.gridList.forEach(item => {
        let a = []
        try {
          a = JSON.parse(item.csc_mapjson)
        } catch (e) {
          console.log(e)
        }
        let path = a
        var polygon = new AMap.Polygon({
          path: path,
          fillColor: '#fff', // 多边形填充颜色
          borderWeight: 2, // 线条宽度，默认为 1
          strokeColor: 'red' // 线条颜色
        })
        this.map.add(polygon)
      })
    },
    // 初始化查询本层级信息
    init () {
      this.loadingShow = true
      if (this.pickID === '') {
        return
      }
      let data = {
        grade: this.pickGrade,
        id: this.pickID
      }
      getGridInfo(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.pickInfo = ret.data.data
          // 处理中心点
          let coordinate = {}
          try {
            let x = this.pickInfo.csc_mapjson.split(',')
            coordinate.lng = x[0]
            coordinate.lat = x[1]
            this.pickInfo.coordinate = coordinate
          } catch (e) {
            this.$Notice.error({ title: '数据错误！', desc: '中心点解析失败！' })
          }
          // 处理缩放程度
          this.autoZoom()
          this.loadingShow = false
          setTimeout(() => {
            this.initMap()
          }, 1000)
          // 选择模板
          this.sceneModal = true
          this.findTemplateList()
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
    },
    // 调整缩放程度
    autoZoom () {
      if (this.pickInfo.grade === '7') {
        this.zoom = 18 // 楼
      } else if (this.pickInfo.grade === '6') {
        this.zoom = 17 // 小区
      } else if (this.pickInfo.grade === '5') {
        this.zoom = 17 // 社区
      } else if (this.pickInfo.grade === '4') {
        this.zoom = 14 // 街道
      } else if (this.pickInfo.grade === '3') {
        this.zoom = 13 // 区
      } else if (this.pickInfo.grade === '8') {
        this.zoom = 18 // 单元
      } else {
        this.zoom = 9
      }
    },
    // 查询模板信息
    findTemplateList () {
      findGridSceneTemplateList().then(ret => {
        if (ret.data.errcode === 0) {
          this.templateDataList = ret.data.data
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    },
    // 根据模板查询信息
    async findSceneInfoList (e) {
      await this.findScenePlaceList(e)
      await this.findSceneLabelList(e)
      this.sceneModal = false
    },
    findScenePlaceList (e) {
      let data = {
        template_id: e.id,
        id: this.pickInfo.id,
        grade: this.pickInfo.grade
      }
      findScenePlaceList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.placeList = ret.data.data
          this.createMassMarks()
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
    },
    findSceneLabelList (e) {
      let data = {
        template_id: e.id,
        id: this.pickInfo.id,
        grade: this.pickInfo.grade
      }
      findSceneLabelList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.labelList = ret.data.data
          this.createHeatMap()
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
    }
  },
  watch: {
    pickID (val) {
      if (val) {
        this.init()
      }
    },
    pickGrade (val) {
      if (val === '2') {
        this.max = 10
      }
      if (val === '3') {
        this.max = 5
      }
      if (val === '4') {
        this.max = 3
      }
      if (val === '5') {
        this.max = 1
      }
    }
  }
}
</script>

<style lang="less" scoped>
//@import url("https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css");

#container {
  padding: 0;
}
.input-card .btn {
  margin-right: 1.2rem;
  width: 9rem;
}
.demo-spin-container{
  display: inline-block;
  width: 100%;
  //height: 400px;
  position: relative;
  //border: 1px solid #eee;
}
</style>
